<template>
  <div
    class="min-h-screen flex items-center justify-center"
    :style="{
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    }">
    <div
      class="backdrop-blur-md bg-white/80 dark:bg-gray-800/80 rounded-xl shadow-2xl p-10 w-96 flex flex-col items-center"
      :class="{ 'animate-fadeIn': showLoginAnimate }">
      <h1 class="text-3xl font-bold mb-8 text-blue-700 dark:text-blue-300">VeloAdmin 登录</h1>
      <form class="flex flex-col gap-5 w-full" @submit.prevent="handleLogin">
        <div>
          <label class="block mb-1 text-gray-800 dark:text-gray-100">用户名/邮箱</label>
          <input v-model="usernameOrEmail" type="text" placeholder="请输入用户名或邮箱" class="input" />
        </div>
        <div>
          <label class="block mb-1 text-gray-800 dark:text-gray-100">密码</label>
          <input v-model="password" type="password" placeholder="请输入密码" class="input" />
        </div>
        <div v-if="captchaEnabled" class="flex items-center gap-2">
          <input v-model="captcha" type="text" placeholder="验证码" class="input flex-1" />
          <img :src="captchaImage" alt="验证码" class="h-8 rounded cursor-pointer border" @click="refreshCaptcha" />
        </div>
        <div class="flex items-center justify-between">
          <label class="flex items-center gap-2 text-gray-700 dark:text-gray-200">
            <input type="checkbox" class="accent-blue-600" v-model="rememberMe" />
            记住密码
          </label>
          <a href="#" class="text-blue-600 dark:text-blue-300 text-sm hover:underline">忘记密码？</a>
        </div>
        <button
          type="submit"
          :disabled="loading"
          class="transition duration-200 border-0 bg-blue-600 text-white dark:bg-blue-400 dark:text-gray-900 px-4 py-2 rounded shadow w-full h-10 mt-2 font-semibold text-lg flex items-center justify-center hover:bg-blue-700 dark:hover:bg-blue-500 hover:shadow-lg transform hover:-translate-y-0.5">
          <span v-if="!loading">登录</span>
          <svg v-else class="animate-spin h-5 w-5 text-white dark:text-gray-900" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
          </svg>
        </button>
        <div v-if="errorMsg" class="text-red-500 text-sm text-center mt-2">
          {{ errorMsg }}
        </div>
      </form>
      <div class="mt-6 text-gray-600 dark:text-gray-300 text-sm">
        还没有账号？<a
          href="#"
          class="text-blue-600 dark:text-blue-300 hover:underline ml-1"
          @click.prevent="showRegister = true"
          >立即注册</a
        >
      </div>
      <!-- 注册弹窗 -->
      <div v-if="showRegister" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
        <div
          class="backdrop-blur-md bg-white/90 dark:bg-gray-800/90 rounded-xl shadow-2xl p-8 w-96 animate-fadeIn relative">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-blue-700 dark:text-blue-300">注册账号</h2>
            <button
              @click="showRegister = false"
              class="flex items-center justify-center w-8 h-8 border-0 text-xl font-bold text-gray-400 bg-transparent transition hover:bg-gray-200 hover:text-blue-600 dark:hover:bg-gray-700 dark:hover:text-blue-300"
              aria-label="关闭">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" d="M6 6l12 12M6 18L18 6" />
              </svg>
            </button>
          </div>
          <form class="flex flex-col gap-4" @submit.prevent="handleRegister">
            <input v-model="regUsername" type="text" placeholder="用户名" class="input" />
            <input v-model="regEmail" type="email" placeholder="邮箱" class="input" />
            <input v-model="regPassword" type="password" placeholder="密码" class="input" />
            <input v-model="regConfirmPassword" type="password" placeholder="重复密码" class="input" />
            <div v-if="captchaEnabled" class="flex items-center gap-2">
              <input v-model="regCaptcha" type="text" placeholder="验证码" class="input" />
              <img
                :src="captchaImage"
                alt="验证码"
                class="h-10 rounded cursor-pointer border self-start"
                @click="refreshCaptcha" />
            </div>

            <button
              type="submit"
              :disabled="regLoading"
              class="transition duration-200 border-0 bg-blue-600 text-white dark:bg-blue-400 dark:text-gray-900 px-4 py-2 rounded shadow w-full h-10 mt-2 font-semibold text-lg flex items-center justify-center hover:bg-blue-700 dark:hover:bg-blue-500 hover:shadow-lg transform hover:-translate-y-0.5">
              <span v-if="!regLoading">注册</span>
              <svg v-else class="animate-spin h-5 w-5 text-white dark:text-gray-900" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
              </svg>
            </button>
            <div v-if="regErrorMsg" class="text-red-500 text-sm text-center mt-2">
              {{ regErrorMsg }}
            </div>
            <div v-if="regSuccessMsg" class="text-green-600 text-sm text-center mt-2">
              {{ regSuccessMsg }}
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { getCaptchaApi, registerApi } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'
import { ConfigHelper } from '@/utils/config'

const showLoginAnimate = ref(false)

const usernameOrEmail = ref('')
const password = ref('')
const captcha = ref('')
const captchaId = ref('')
const captchaImage = ref('')
const rememberMe = ref(false)
const loading = ref(false)
const errorMsg = ref('')
const router = useRouter()
const userStore = useUserStore()
const themeStore = useThemeStore()
const captchaEnabled = ref(true) // 默认启用验证码

// 获取验证码
async function fetchCaptcha() {
  try {
    const res = await getCaptchaApi()
    captchaId.value = res.captchaId
    captchaImage.value = 'data:image/svg+xml;utf8,' + encodeURIComponent(res.image)
    captcha.value = ''
  } catch {
    captchaImage.value = ''
    captchaId.value = ''
  }
}

function refreshCaptcha() {
  // 如果启用了验证码，则刷新验证码
  if (captchaEnabled.value) fetchCaptcha()
}

async function handleLogin() {
  loading.value = true
  // 根据验证码配置决定是否传递验证码参数
  const res = await userStore.login(
    usernameOrEmail.value,
    password.value,
    captcha.value,
    captchaId.value,
    rememberMe.value,
  )

  if (res.success) {
    router.push('/')
  } else {
    errorMsg.value = res.message || '登录失败，请检查用户名、密码或验证码'
    refreshCaptcha()
  }
  loading.value = false
}

// 注册弹窗逻辑
const showRegister = ref(false)
const regUsername = ref('')
const regEmail = ref('')
const regPassword = ref('')
const regConfirmPassword = ref('')
const regCaptcha = ref('')
const regLoading = ref(false)
const regErrorMsg = ref('')
const regSuccessMsg = ref('')

async function handleRegister() {
  regErrorMsg.value = ''
  regSuccessMsg.value = ''
  regLoading.value = true
  try {
    // 根据验证码配置决定是否传递验证码参数
    const registerParams = [
      regUsername.value,
      regEmail.value,
      regPassword.value,
      regConfirmPassword.value,
      captchaEnabled.value ? regCaptcha.value : '',
      captchaEnabled.value ? captchaId.value : '',
    ]
    const res = await userStore.register(
      regUsername.value,
      regEmail.value,
      regPassword.value,
      regConfirmPassword.value,
      regCaptcha.value,
      captchaId.value,
    )
    if (res.success) {
      regSuccessMsg.value = res.message || '注册成功，请登录！'
      setTimeout(() => {
        showRegister.value = false
        regUsername.value = ''
        regEmail.value = ''
        regPassword.value = ''
        regConfirmPassword.value = ''
        regCaptcha.value = ''
        regSuccessMsg.value = ''
      }, 1500)
    } else {
      regErrorMsg.value = res.message || '注册失败，请重试'
    }
    refreshCaptcha()
  } finally {
    regLoading.value = false
  }
}

// 主题切换联动
watch(
  () => themeStore.isDark,
  (val) => {
    themeStore.setTheme(val)
  },
)

onMounted(async () => {
  themeStore.initTheme()
  showLoginAnimate.value = true
  // 获取验证码配置
  captchaEnabled.value = await ConfigHelper.getCaptchaEnabled()

  // 如果启用了验证码，则加载验证码
  if (captchaEnabled.value) {
    fetchCaptcha()
  }

  // 检查登录状态，如果已登录则重定向到首页
  if (userStore.isLoggedIn) {
    // 已经登录但还在登录页，直接跳转到首页
    router.push('/')
  }
})
</script>

<style scoped>
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(40px);
  }

  to {
    opacity: 1;
    transform: none;
  }
}

.animate-fadeIn {
  animation: fadeIn 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}
</style>
